package com.hxm.meizi.ui.activity;

import android.graphics.Color;
import android.os.Build;
import android.os.Environment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.hxm.meizi.R;
import com.hxm.meizi.adapter.ImagePreAdapter;
import com.hxm.meizi.app.Constants;
import com.hxm.meizi.entity.ImageUrl;
import com.hxm.meizi.http.BaseSubscriber;
import com.hxm.meizi.http.HttpRequest;
import com.hxm.meizi.http.NetException;
import com.hxm.meizi.widget.PreViewPager;
import com.lcodecore.tkrefreshlayout.utils.DensityUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import okhttp3.ResponseBody;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Hxm on 2017/2/20.
 * 图片预览
 */

public class ImagePreviewActivity extends BaseActivity {

    private PreViewPager viewPager;
    private ArrayList<ImageUrl> imageUrls;
    private ImagePreAdapter adapter;
    private int currentPosition;
    private TextView saveImage, imageIndex;

    @Override
    protected void beforeSetContentView() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        super.beforeSetContentView();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.avtivity_image_preview;
    }

    @Override
    protected void initView() {
        registNetStatusReceiver();
        saveImage = (TextView) findViewById(R.id.tv_save);
        imageIndex = (TextView) findViewById(R.id.tv_current_position);
        viewPager = (PreViewPager) findViewById(R.id.view_pager);
        viewPager.setPageMargin(DensityUtil.dp2px(this, 15));
    }

    @Override
    protected void initData() {
        imageUrls = getIntent().getParcelableArrayListExtra("item_data");
        currentPosition = getIntent().getIntExtra("currentPosition", 0);
        adapter = new ImagePreAdapter(this, imageUrls);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(currentPosition, false);
        imageIndex.setText(getString(R.string.preview_image_count, currentPosition + 1, imageUrls.size()));
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                imageIndex.setText(getString(R.string.preview_image_count, position + 1, imageUrls.size()));
            }
        });
        saveImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadImage(imageUrls.get(currentPosition).getUrl());
            }
        });
    }

    @Override
    public void onBackPressed() {
        finish();
    }

    private void downloadImage(final String url) {
        LogUtils.i("hxm", url);
        HttpRequest.getInstance().downloadImage(url)
                .subscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, Boolean>() {
                    @Override
                    public Boolean call(ResponseBody responseBody) {
                        return writeToDisk(responseBody, url);
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Boolean>() {
                    @Override
                    public void onError(NetException.ResponseThrowable e) {
                        Log.i("error", e.message + e.toString());
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        if (aBoolean) {
                            ToastUtils.showLongToast("已保存到" + Constants.SAVE_PATH + "目录下");
                        } else {
                            ToastUtils.showLongToast("保存失败");
                        }
                    }
                });
    }

    private boolean writeToDisk(ResponseBody body, String url) {
        // 判断是否挂载了SD卡
        String storageState = Environment.getExternalStorageState();
        if (storageState.equals(Environment.MEDIA_MOUNTED)) {
            File savedir = new File(Constants.SAVE_PATH);
            if (!savedir.exists()) {
                savedir.mkdirs();
            }
        } else {
            return false;
        }
        String name = url.hashCode() + ".jpg";
        File SAVE_PATH = new File(Constants.SAVE_PATH, name);
        InputStream inputStream;
        OutputStream outputStream = null;
        //缓冲大小
        byte[] readByte = new byte[4096];
        inputStream = body.byteStream();
        try {
            outputStream = new FileOutputStream(SAVE_PATH);
            while (true) {
                int read = inputStream.read(readByte);
                if (read == -1) {
                    break;
                }
                outputStream.write(readByte, 0, read);
            }
            outputStream.flush();
            return true;
        } catch (IOException e) {
            LogUtils.i("hxm", e.toString());
            return false;
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
